/****************************************************************************
 *
 * Copyright (C) 2003-2010 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.server;

import java.util.ArrayList;
import java.util.HashMap;

import nfse.NetFSEUtil;
import nfse.gui.record.FlexRecord;
import nfse.gui.record.FlexRecordField;

public class RecordBuilderUtil {

    private ArrayList<SQLField> fields = new ArrayList<SQLField>();

    private HashMap<String, Integer> fieldMap = new HashMap<String, Integer>();

    public static final int VARCHAR = 1;

    public static final int TIMESTAMP = 2;

    public static final int INTEGER = 3;

    public static final int BIGINT = 4;

    public static final int INET = 5;

    public static final int TEXT = 6;

    public static final int FLOAT = 7;

    public SQLField addColumn(String header, String name, int fieldType, int option) {
        SQLField field = new SQLField(header, name, null, fieldType, option);
        fields.add(field);
        fieldMap.put(name, fields.size() - 1);
        return field;
    }

    public SQLField addColumn(String header, String name, int fieldType) {
        return addColumn(header, name, fieldType, -1);
    }

    public SQLField addColumn(String name, int fieldType) {
        return addColumn(name, name, fieldType, -1);
    }

    public SQLField addColumn(String name, int fieldType, int option) {
        return addColumn(name, name, fieldType, -1);
    }

    public void setFieldValue(int index, String value) {
        SQLField field = fields.get(index);
        field.value = value;
    }

    public void setFieldValue(String column, String value) throws Exception {
        Integer idx = fieldMap.get(column);
        if (idx == null)
            throw new Exception("Invalid column name: '" + column + "'");
        SQLField field = fields.get(idx);
        field.value = value;
    }

    public String getCopySQL() {
        StringBuilder sql = new StringBuilder();

        boolean first = true;
        for (SQLField field : fields) {
            if (field.hexEncode)
                field.value = NetFSEUtil.convertToHex(field.value);

            if (!first)
                sql.append("\t");
            else
                first = false;

            if ((field.value != null) && (!"null".equals(field.value))) {

                switch (field.fieldType) {
                case RecordBuilderUtil.INET:
                case RecordBuilderUtil.BIGINT:
                case RecordBuilderUtil.INTEGER:
                case RecordBuilderUtil.FLOAT:

                    sql.append(field.value);
                    break;
                case RecordBuilderUtil.TIMESTAMP:
                case RecordBuilderUtil.TEXT:
                    // sql.append("'");
                    sql.append(field.value);
                    // sql.append("'");
                    break;
                case RecordBuilderUtil.VARCHAR:
                    if (field.value.length() > field.option)
                        field.value = field.value.substring(0, field.option);
                    // sql.append("'");
                    sql.append(field.value);
                    // sql.append("'");
                    break;
                }
            } else {
                sql.append("NULL");
            }
        }
        sql.append(")");
        return sql.toString();
    }

    public String getInsertSQL(String table) {
        StringBuilder sql = new StringBuilder();
        sql.append("insert into " + table + " values (");
        boolean first = true;
        for (SQLField field : fields) {
            if (field.hexEncode)
                field.value = NetFSEUtil.convertToHex(field.value);

            if (!first)
                sql.append(",");
            else
                first = false;
            if ((field.value != null) && (!"null".equals(field.value))) {
                switch (field.fieldType) {
                case RecordBuilderUtil.BIGINT:
                case RecordBuilderUtil.INTEGER:
                case RecordBuilderUtil.FLOAT:
                    sql.append(field.value);
                    break;
                case RecordBuilderUtil.INET:
                case RecordBuilderUtil.TIMESTAMP:
                    sql.append("'");
                    sql.append(field.value);
                    sql.append("'");
                    break;
                case RecordBuilderUtil.TEXT:
                    if (field.option >= 0 && field.value.length() > field.option)
                        field.value = field.value.substring(0, field.option);
                    sql.append("'");
                    sql.append(field.value);
                    sql.append("'");
                    break;
                case RecordBuilderUtil.VARCHAR:
                    if (field.option >= 0 && field.value.length() > field.option)
                        field.value = field.value.substring(0, field.option);
                    sql.append("'");
                    sql.append(field.value);
                    sql.append("'");
                    break;
                }
            } else {
                sql.append("NULL");
            }
        }
        sql.append(")");
        return sql.toString();
    }

    public String getCreateSQL(String table) {
        StringBuilder sql = new StringBuilder();
        sql.append("create table " + table + " (");
        boolean first = true;
        for (SQLField field : fields) {
            if (!first)
                sql.append(",");
            else
                first = false;
            sql.append(field.column);
            sql.append(" ");
            switch (field.fieldType) {
            case RecordBuilderUtil.BIGINT:
                sql.append("bigint");
                break;
            case RecordBuilderUtil.INTEGER:
                sql.append("integer");
                break;
            case RecordBuilderUtil.INET:
                sql.append("inet");
                break;
            case RecordBuilderUtil.TIMESTAMP:
                sql.append("timestamp");
                break;
            case RecordBuilderUtil.TEXT:
                sql.append("text");
                break;
            case RecordBuilderUtil.FLOAT:
                sql.append("float");
                break;
            case RecordBuilderUtil.VARCHAR:
                sql.append("varchar(");
                sql.append(field.option + ")");
                break;
            }
        }
        sql.append(")");
        return sql.toString();
    }

    public FlexRecordField[] getFlexRecordFields() {
        ArrayList<FlexRecordField> tempFields = new ArrayList<FlexRecordField>(20);
        for (int i = 0; i < fields.size(); i++) {
            SQLField field = fields.get(i);
            if (field.header != null) { // Ignore anything with a null column
                // header
                int type = FlexRecordField.TYPE_STRING;
                switch (field.fieldType) {
                case RecordBuilderUtil.FLOAT:
                    type = FlexRecordField.TYPE_FLOAT;
                    break;
                case RecordBuilderUtil.BIGINT:
                    type = FlexRecordField.TYPE_LONG;
                    break;
                case RecordBuilderUtil.INTEGER:
                    type = FlexRecordField.TYPE_INT;
                    break;
                }
                tempFields.add(new FlexRecordField(field.header, field.column, type, field.subtype));
            }
        }

        FlexRecordField[] temp = new FlexRecordField[tempFields.size()];
        for (int i = 0; i < temp.length; i++)
            temp[i] = tempFields.get(i);

        return temp;
    }

    /***************************************************************************
     * This method transforms the parsed event into a FlexRecord for use in
     * displaying the record in the web interface. This method is abstract and
     * therefore must be implemented by each individual event type.
     * 
     * @return The event in the form of a nfse.gui.record.FlexRecord that can be
     *         passed to the web interface.
     */
    public FlexRecord getFlexRecord(int sensor) {
        ArrayList<String> values = new ArrayList<String>(20);
        FlexRecord temp = new FlexRecord();
        temp.sensorID = sensor;

        for (int i = 0; i < fields.size(); i++) {
            SQLField f = fields.get(i);
            if (f.header != null) {
                if (f.fieldType == RecordBuilderUtil.TEXT || f.fieldType == RecordBuilderUtil.VARCHAR)
                    values.add(NetFSEUtil.webify(f.value));
                else
                    values.add(f.value);
            }
        }
        temp.values = new String[values.size()];
        for (int i = 0; i < temp.values.length; i++)
            temp.values[i] = values.get(i);
        return temp;
    }

    public class SQLField {

        String header = null;

        String value = null;

        String column = null;

        int fieldType = -1;

        int option = 500;

        int subtype = FlexRecordField.SUB_TYPE_NONE;

        boolean hexEncode = false;

        protected SQLField(String header, String column, String value, int fieldType, int option) {
            this.value = value;
            this.column = column;
            this.fieldType = fieldType;
            this.option = option;
            this.header = header;
            this.subtype = getDefaultSubtype();
        }

        public void setSubtype(int subtype) {
            this.subtype = subtype;
        }

        private int getDefaultSubtype() {
            int option = -1;
            if (fieldType == RecordBuilderUtil.INET)
                option = FlexRecordField.SUB_TYPE_IP_ADDR;
            else if (fieldType == RecordBuilderUtil.TIMESTAMP)
                option = FlexRecordField.SUB_TYPE_TIMESTAMP;
            return option;
        }

        /**
         * @return the hexEncode
         */
        public boolean isHexEncoded() {
            return hexEncode;
        }

        /**
         * @param hexEncode
         *            the hexEncode to set
         */
        public void setHexEncoded(boolean hexEncode) {
            this.hexEncode = hexEncode;
        }

    }
}
